// This example advertises for 5 minutes after
// - boot
// - disconnect
// and then stops advertising.
package main

import (
	"fmt"
	"time"

	"go_ble/bluetooth"
)

var adapter = bluetooth.DefaultAdapter

var (
	localName = "Jack Test Ble"

	batteryLevel uint8 = 75 // 75%
	battery      bluetooth.Characteristic
)

func main() {
	println("starting")
	// common.HplcDataSendChan = make(chan []byte)
	// common.HplcDataRecvChan = make(chan []byte)
	myChan := make(chan int)
	must("enable BLE stack", adapter.Enable())
	adv := adapter.DefaultAdvertisement()
	must("config adv", adv.Configure(bluetooth.AdvertisementOptions{
		LocalName:    localName,
		ServiceUUIDs: []bluetooth.UUID{bluetooth.ServiceUUIDVolumeControl},
	}))
	adapter.SetConnectHandler(func(device bluetooth.Device, connected bool) {
		if connected {
			// println("connected, not advertising...")
			fmt.Printf("device:--> Name = \"%s\" MAC = %s  ----------->>> Connected\n", device.Name, device.Address.MACAddress.MAC.String())
		} else {
			// println("disconnected, advertising...")
			fmt.Printf("device:--> Name = \"%s\" MAC = %s  ----------->>> Disconnected\n", device.Name, device.Address.MACAddress.MAC.String())
		}
	})
	must("start adv", adv.Start())
	count := 0

	fmt.Print("add service")
	must("add service", adapter.AddService(&bluetooth.Service{
		UUID: bluetooth.ServiceUUIDBattery,
		Characteristics: []bluetooth.CharacteristicConfig{
			{
				Handle: &battery,
				UUID:   bluetooth.CharacteristicUUIDBatteryLevel,
				Value:  []byte{byte(batteryLevel)},
				Flags:  bluetooth.CharacteristicReadPermission | bluetooth.CharacteristicWritePermission | bluetooth.CharacteristicNotifyPermission,
				WriteEvent: func(client bluetooth.Connection, offset int, value []byte) {
					count++
					fmt.Printf("\n蓝牙接收到数据  count = %d,offset = %d\n", count, offset)
					fmt.Printf("client: %v\n", client)
					fmt.Println(client)
					fmt.Print(value)
					fmt.Print("\n")
					value = append(value, '\n')
					// time.Sleep(time.Millisecond * 100)
					// common.HplcDataSendChan <- value
					myChan <- 999
				},
			},
		},
	}))

	// for {
	// 	println("tick", time.Now().Format("04:05.000"))
	// 	value := <-myChan
	// 	// random variation in batteryLevel
	// 	batteryLevel = randomInt(65, 85)
	// 	time.Sleep(time.Millisecond * 100)
	// 	// and push the next notification
	// 	if value == 9527 {
	// 		battery.Notify([]byte("12345678"))
	// 	}

	// 	time.Sleep(time.Second)
	// }

	// for value := range common.HplcDataRecvChan {
	for value := range myChan {
		// logger.Debug("myChan act")
		if value == 999 {
			battery.Notify([]byte("12345678900987654321"))
		}

		// battery.Notify(value)
		println("tick", time.Now().Format("04:05.000"))
		time.Sleep(time.Millisecond * 100)
	}
}

func must(action string, err error) {
	if err != nil {
		panic("failed to " + action + ": " + err.Error())
	}
}
